import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app/bean/file_path_entity.dart';
import 'package:flutter_app/bean/problem_by_code_entity.dart';
import 'package:flutter_app/r.dart';
import 'package:flutter_app/values/MyColors.dart';
import 'package:flutter_app/widget/ImagesGridviewWidget.dart';
import 'package:flutter_app/widget/custom_app_bar.dart';
import 'package:flutter_app/widget/empty_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swipe_action_cell/core/cell.dart';
import 'package:get/get.dart';
import 'package:image_pickers/image_pickers.dart';

import 'query_detail_logic.dart';

/**
 * @Description: 问题详情
 * @Author: 下雨了
 * @CreateDate: 2022-7-14 16:19:52
 * @UpdateUser: 更新者
 * @UpdateDate:  2022-7-14 16:19:52
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
///
class QueryDetailPage extends StatefulWidget {
  final String title;
  const QueryDetailPage({Key? key, required this.title}) : super(key: key);

  @override
  _QueryDetailPageState createState() => _QueryDetailPageState();
}

class _QueryDetailPageState extends State<QueryDetailPage> {
  final logic = Get.put(QueryDetailLogic());
  final state = Get.find<QueryDetailLogic>().state;
  var actionKey = GlobalKey();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<QueryDetailLogic>(builder: (logic) {
      return Scaffold(
        backgroundColor: MyColors.FFF1F1F1,
        appBar: MyAppBar(context, title: "问题详情"),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: EdgeInsets.only(left: 16.r, top: 12.r, bottom: 10.r),
              child: Text(state.typeName, style: TextStyle(color: MyColors.FF010101, fontSize: 16.sp),),
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    (state.problemByCodeEntity?.length ?? 0) > 0 ?
                    ListView.builder(
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      padding: EdgeInsets.only(top: 0),
                      itemCount: state.problemByCodeEntity?.length ?? 0,
                      itemBuilder: (BuildContext context, int index) {
                        return ListItem(state.problemByCodeEntity![index], index);
                      },
                    ) : EmptyView(),
                    // 页脚
                    Visibility(
                      visible: state.taskStatus,
                      child: Footer(),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  Widget ListItem(ProblemByCodeEntity item, int index) {
    return Container(
      height: 110.r,
      margin: EdgeInsets.only(left: 16.r, right: 16.r, bottom: 10.r),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4.r),
        boxShadow: [
          BoxShadow(
              color: Color(0x1A5F5F5F), blurRadius: 1, spreadRadius: 0.05)
        ]),
      child: SwipeActionCell(
        key: ValueKey(item),
        backgroundColor: Colors.white,
        trailingActions: <SwipeAction>[
          SwipeAction(
            title: "删除",
            style: TextStyle(color: MyColors.FFC67517, fontSize: 13.sp),
            widthSpace: 70.r,
            nestedAction: SwipeNestedAction(
              icon: Image.asset(R.assetsImgIcon83, height: 40.r,),
              title: "确定删除",
              nestedWidth: 70.r
            ),
            icon: Image.asset(R.assetsImgIcon83, height: 40.r,),
            onTap: (CompletionHandler handler) async {
              await handler(false);
              logic.postDeleteProblem(index);
            },
            color: MyColors.FFF1F1F1,
          ),
          SwipeAction(
            title: "编辑",
            style: TextStyle(color: MyColors.FF2763B9, fontSize: 13.sp),
            widthSpace: 70.r,
            icon: Image.asset(R.assetsImgIcon82, height: 40.r,),
            onTap: (CompletionHandler handler) async {
              handler(false);
              showBottomDialog(index: index);
            },
            color: MyColors.FFF1F1F1,
          ),
        ],
        child: InkWell(
          child: Row(
            children: [
              Container(
                margin: EdgeInsets.only(left: 15.r, top: 15.r, right: 8.r, bottom: 15.r),
                width: 80.r,
                height: 80.r,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Image.network(item.fileList?.first.thumbnailPath ?? "", fit: BoxFit.cover, width: 80.r,),
                    Visibility(
                      visible: (state.problemByCodeEntity![index].fileList?.length ?? 0) > 1,
                      child: Container(
                        width: 80.r,
                        height: 80.r,
                        color: Colors.black12,
                        alignment: Alignment.center,
                        child: Text("+${state.problemByCodeEntity![index].fileList?.length ?? 0}", style: TextStyle(color: MyColors.FFFFFFFF, fontSize: 16.sp),),
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: Container(
                  padding: EdgeInsets.only(top: 15.r, right: 8.r, bottom: 15.r),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(item.content ?? "",
                        maxLines: 2,
                        style: TextStyle(color: MyColors.FF333333, fontSize: 14.sp),
                      ),
                      Row(
                        children: [
                          Image.asset(R.assetsImgIcon78, width: 14.r,),
                          SizedBox(width: 2.r,),
                          Text(item.createName ?? "", style: TextStyle(color: MyColors.FF888888, fontSize: 13.sp),),
                        ],
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
          onTap: () {
            showBottomDialog(index: index);
          },
        ),
      ),
    );
  }

  // 底部
  Widget Footer() {
    return Container(
      height: 65.r,
      width: Get.width,
      margin: EdgeInsets.only(left: 16.r, right: 16.r, bottom: 15.r),
      decoration: BoxDecoration(
        border: Border.all(
          color: MyColors.FF999999,
          width: 0.5.r,
          style: BorderStyle.solid
        ),
      ),
      child: InkWell(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(R.assetsImgIcon79, width: 21,),
            SizedBox(width: 9.r,),
            Text("新增事项", style: TextStyle(color: MyColors.FF666666, fontSize: 14.sp),)
          ],
        ),
        onTap: () {
          showBottomDialog();
        },
      ),
    );
  }

  // 底部弹窗
  void showBottomDialog({int? index}) {
    // 输入框重新赋值
    logic.reassign(index: index);
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(topLeft: Radius.circular(13.33.r), topRight: Radius.circular(13.33.r))
      ),
      // isScrollControlled属性，设置为true，弹窗会覆盖整个手机。设置为false，弹窗大概是整个屏幕的9/16高。
      isScrollControlled: true,
      builder: (BuildContext context) {
        return ConstrainedBox(
          constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 8.0 / 10.0),
          child: GestureDetector(
            child: Column(
              children: [
                Container(
                  margin: EdgeInsets.only(top: 14.r, bottom: 14.r, left: 16.r, right: 16.r),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text("新增事项", style: TextStyle(color: MyColors.FF333333, fontSize: 18.sp),),
                      Visibility(
                        visible: index!= null,
                        child: Row(
                          children: [
                            Image.asset(R.assetsImgIcon78, width: 14.r,),
                            SizedBox(width: 2.r,),
                            Text("填报人：${index != null ? state.problemByCodeEntity![index].createName : ""}")
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Divider(thickness: 0.5.r, height: 0, color: MyColors.FFDDDDDD,),
                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        IgnorePointer(
                          ignoring: !logic.editState(index: index),
                          child: Container(
                            margin: EdgeInsets.only(top: 14.r, left: 16.r, right: 16.r),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                // Text("二级部门", style: TextStyle(color: MyColors.FF666666, fontSize: 14.sp,),),
                                // Container(
                                //   margin: EdgeInsets.only(top: 8.r),
                                //   child: TextField(
                                //     decoration: InputDecoration(
                                //       // 去除内边距
                                //       contentPadding: EdgeInsets.all(0),
                                //       // 去掉底部下划线
                                //       border: InputBorder.none,
                                //       hintText: "请输入二级部门名称（选填）。",
                                //       hintStyle: TextStyle(color: MyColors.FFBBBBBB, fontSize: 13.sp),
                                //       helperStyle: TextStyle(color: MyColors.FF999999, fontSize: 11.sp),
                                //       // 右侧内图标
                                //       suffixIcon: Visibility(
                                //         visible: state.listOrg.length > 0,
                                //         child: SizedBox(
                                //           width: 8.r,
                                //           height: 8.r,
                                //           child: IconButton(
                                //             key: actionKey,
                                //             padding: EdgeInsets.all(0.r),
                                //             icon: Image.asset(R.assetsImgIcon48, width: 7.r,),
                                //             onPressed: () {
                                //               BrnPopupListWindow.showPopListWindow(
                                //                 context, actionKey,
                                //                 offset: 0,
                                //                 data: state.listOrg,
                                //                 onItemClick: (int _, String value) {
                                //                   logic.textRemark.text = value;
                                //                   if (index != null) {
                                //                     state.problemByCodeEntity![index].remark = value;
                                //                   } else {
                                //                     logic.editRemarkStr = value;
                                //                   }
                                //                   return false;
                                //                 }
                                //               );
                                //             },
                                //           ),
                                //         ),
                                //       ),
                                //     ),
                                //     // 光标颜色
                                //     cursorColor: MyColors.FF010101,
                                //     // 光标宽度
                                //     cursorWidth: 1,
                                //     minLines: 1,
                                //     maxLines: 1,
                                //     maxLength: 20,
                                //     autofocus: false,  // 自动对焦
                                //     controller: logic.textRemark,
                                //     style: TextStyle(
                                //         color: MyColors.FF010101,
                                //         fontSize: 14.sp,
                                //         fontWeight: FontWeight.w500),
                                //     onChanged: (value) {
                                //       if (index != null) {
                                //         state.problemByCodeEntity![index].remark = value;
                                //       } else {
                                //         logic.editRemarkStr = value;
                                //       }
                                //     },
                                //   ),
                                // ),
                                Container(
                                  // margin: EdgeInsets.only(top: 8.r),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text("详细说明", style: TextStyle(color: MyColors.FF666666, fontSize: 14.sp,),),
                                      SizedBox(
                                        width: 75.r,
                                        height: 20.r,
                                        child: TextButton.icon(
                                          style: TextButton.styleFrom(
                                            padding: EdgeInsets.all(0),
                                            //设置按钮的大小
                                            minimumSize: Size(60.r, 12.r),
                                          ),
                                          icon: Container(
                                              margin: EdgeInsets.only(top: 2),
                                              child: Image.asset(R.assetsImgIcon24, width: 7.5.r,)),
                                          label: Text("查看示例", style: TextStyle(color: MyColors.FF2763B9, fontSize: 12.sp),),
                                          onPressed: () {
                                            String message = "11月29号上午9:35分，省某厅1026室计划处王某在电脑上玩纸牌游戏。";
                                            BrnDialogManager.showSingleButtonDialog(context,
                                                label: "复制",
                                                title: '填写示例',
                                                message: message, onTap: () {
                                                  Clipboard.setData(ClipboardData(text: message));
                                                  Get.back();
                                                });
                                          },
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 8.r),
                                  child: TextField(
                                    decoration: InputDecoration(
                                      // 去除内边距
                                      contentPadding: EdgeInsets.zero,
                                      // 去掉底部下划线
                                      border: InputBorder.none,
                                      hintText: "详细注明发现问题的时间、房间号、违规种类、干部职工姓名、处室等具体信息。",
                                      hintStyle: TextStyle(color: MyColors.FFBBBBBB, fontSize: 13.sp),
                                      helperStyle: TextStyle(color: MyColors.FF999999, fontSize: 11.sp),
                                    ),
                                    // 光标颜色
                                    cursorColor: MyColors.FF010101,
                                    // 光标宽度
                                    cursorWidth: 1,
                                    minLines: 4,
                                    maxLines: 5,
                                    maxLength: 1000,
                                    autofocus: false,  // 自动对焦
                                    controller: logic.textCtrl,
                                    style: TextStyle(
                                        color: MyColors.FF010101,
                                        fontSize: 14.sp,
                                        fontWeight: FontWeight.w500),
                                    onChanged: (value) {
                                      if (index != null) {
                                        state.problemByCodeEntity![index].content = value;
                                      } else {
                                        logic.editContentStr = value;
                                      }
                                    },
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        Container(
                          child: Container(
                            padding: EdgeInsets.only(top: 14.r, bottom: 14.r, left: 16.r, right: 16.r),
                            child: ImagesGridviewWidget(
                              filePathList: index != null ? state.problemByCodeEntity![index].fileList : null,
                              resultList: index != null ? state.problemByCodeEntity![index].imagesList : logic.imagesList,
                              isWriteAuth: logic.editState(index: index),
                              // isOpenPhoto: logic.mainLogic.state.pinPutState.value,
                              isOpenFile: logic.mainLogic.state.pinPutState.value,
                              isOpenSelect: true,
                              dirName: logic.groupId,
                              onMediaResultsCallback: (List<Media> imagesList, List<FilePathEntity> filePathList) {
                                if (index != null) {
                                  if (imagesList.length > 0) {
                                    state.problemByCodeEntity![index].imagesList = imagesList;
                                  }
                                  if (filePathList.length > 0) {
                                    state.problemByCodeEntity![index].fileList = filePathList;
                                  }
                                } else {
                                  if (imagesList.length > 0) {
                                    logic.imagesList = imagesList;
                                  }
                                  // if (filePathList.length > 0) {
                                  //   logic.filePathList = filePathList;
                                  // }
                                }
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  child: Container(
                    width: Get.width,
                    color: Colors.white,
                    padding: EdgeInsets.only(top: 5.r, bottom: 5.r, left: 16.r, right: 16.r),
                    child: SafeArea(
                      child: Visibility(
                        visible: logic.editState(index: index),
                        child: SizedBox(
                          height: 40.r,
                          child: TextButton(
                            style: TextButton.styleFrom(
                              backgroundColor: MyColors.FF2763B9,
                              padding: EdgeInsets.all(0),
                            ),
                            child: Text("保存", style: TextStyle(color: MyColors.FFFFFFFF, fontSize: 14.sp),),
                            onPressed: () {
                              logic.save(index: index);
                            },
                          ),
                        ),
                      ),
                    ),
                  ),
                )
              ],
            ),
            onTap: () {
              // 空白处取消TextField焦点
              FocusScopeNode currentFocus = FocusScope.of(context);
              if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
                FocusManager.instance.primaryFocus!.unfocus();
              }
            },
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    Get.delete<QueryDetailLogic>();
    super.dispose();
  }
}